package com.liu.UCenterService.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.liu.UCenterService.entity.UcenterMember;
import com.liu.UCenterService.service.UcenterMemberService;
import com.liu.UCenterService.utils.ConstantWxUtil;
import com.liu.UCenterService.utils.HttpClientUtils;
import com.liu.serviceBase.exception.MyException;
import com.liu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * **************
 * 项目名称: testgulili <br/>
 * 文件名称:  <br/>
 * 文件描述: 这里添加您的类文件描述，说明当前文件要包含的功能。 <br/>
 * 文件创建：刘世锦 <br/>
 * 创建时间: 2022/2/7 <br/>
 *
 * @version v1.0 <br/>
 * @update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]<br/>
 * *************
 */
@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class UcenterWxController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    @GetMapping("callback")
    public String getWxUserInfo(String code, String state, HttpSession session) {
         String IndexUrl = "http://localhost:3000";
        //得到授权临时票据code
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
//配置参数
        String AccessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtil.APP_ID,
                ConstantWxUtil.APP_SECRET,
                code);
//          http的get请求
        String AccessResult = null;
        try {
            AccessResult = HttpClientUtils.get(AccessTokenUrl);
            System.out.println("accessToken==>>"+AccessResult);

        } catch (Exception e) {
            throw new MyException(20001, "获取access_token失败");
        }
        if (AccessResult==null){
            throw  new MyException(20001,"AccessResult为空！");
        }
        JSONObject jsonObject = JSON.parseObject(AccessResult);

        String accessToken = (String) jsonObject.get("access_token");
        String openid = (String) jsonObject.get("openid");
//        openid 即为用户微信的唯一标识id
//        若此时数据库查不到，则为新用户需要注册（数据库新添值）
        UcenterMember member = ucenterMemberService.getbyOpenid(openid);

//     todo   若为新用户则访问微信服务器获取其初始信息：
        if (member==null){

        //访问微信的资源服务器，获取用户信息
        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
//        访问userinfo的URL
        String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);

        String UserInfo = null;
        try {
             UserInfo = HttpClientUtils.get(userInfoUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (UserInfo==null){
            throw  new MyException(20001,"UserInfo为空！");
        }
        System.out.println("UserInfo==========" + UserInfo);
        Gson gson = new Gson();
        HashMap hashMap = gson.fromJson(UserInfo, HashMap.class);
        String nickname = (String) hashMap.get("nickname");
        String headimgurl = (String) hashMap.get("headimgurl");

            member = new UcenterMember();
            member.setOpenid(openid)
                    .setNickname(nickname)
                    .setAvatar(headimgurl);

            boolean save = ucenterMemberService.save(member);
            System.out.println(save?"微信用户注册登录成功":"微信用户注册登录失败");
            if (!save){
                throw  new MyException(20001,"微信用户注册登录失败！");
            }

        }

        //使用jwt根据member对象生成token字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        System.out.println("jwtToken:"+jwtToken);
        //最后：返回首页面，通过路径传递token字符串
//        return "redirect:http://localhost:3000?token="+jwtToken;
            return "redirect:" + IndexUrl+"?token="+jwtToken;

    }



    @GetMapping("/Wxlogin")
    public String getWxQRcode(){
        String Url = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s"+
                "#wechat_redirect";

        String redirectUrl = ConstantWxUtil.REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String lastUrl = String.format(Url,
                ConstantWxUtil.APP_ID,
                ConstantWxUtil.REDIRECT_URL,
                "testgulili"
        );
        System.out.println(lastUrl);
        return "redirect:"+lastUrl;
    }

}
